package bTree.LeetCode;

import javax.swing.tree.TreeNode;
import java.util.*;

public class 二叉树的锯齿形层序遍历 {
    List<List<Integer>> res = new ArrayList<>();

    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        if (root == null) {
            return res;
        }
        bfs(root);
        int flag=1;
        for (List<Integer> re : res) {
            if(flag%2==1){
                Collections.reverse(re);
            }
        }
        return res;
    }

    private void bfs(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            int len = queue.size();
            List<Integer> list = new ArrayList<>();
            for (int i = 0; i < len; i++) {
                list.add(queue.peek().val);
                if (queue.peek().left != null) {
                    queue.add(queue.peek().left);
                }
                if (queue.peek().right != null) {
                    queue.add(queue.peek().right);
                }
            }
            queue.poll();
            res.add(list);
        }
    }
}